package org.testmyapp;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.testmyapp.session.SessionForUser;

import com.sun.servicetag.UnauthorizedAccessException;

public abstract class SessionCheckedHttpServlet extends HttpServlet {

	public static final String redirectTo = "LoginServlet";
	protected static final String priortisedTasks = "priortisedTasks";
	protected static final String responseType = "text/html";
	protected static final String processServlet = "TaskServlet";
	protected static final String overviewServlet = "Overview";
	
	private String servletName = null;

	private void checkSession(SessionForUser sfu) throws IllegalStateException {
		if (sfu.getUser() == null || "".equals(sfu.getUser())) {
			System.out.println("Unauthorized Acces to page, return to login");
			throw new UnauthorizedAccessException("Unauthorized Acces to page, return to login");
		}
	}

	public void redirectIfSessionCheckFails(HttpServletRequest req,
			HttpServletResponse resp, SessionForUser sessionUser)
			throws ServletException, IOException {
		try {
			checkSession(sessionUser);
		} catch (UnauthorizedAccessException e) {
			req.getRequestDispatcher(redirectTo).forward(req, resp);
		}
	}
	
	protected void print(List<String> html, PrintWriter writer) {
		for (String s : html) {
			writer.println(s);
		}
	}
	
	public void logoutSessionCheckAndExecution(SessionForUser sfu, HttpServletRequest req, HttpServletResponse resp) {
		String logoutParam = req.getParameter("logout");
		if (logoutParam == null || !logoutParam.equals("logout")) {
			return;
		}
		
		sfu.setLoginTime(null);
		sfu.setUser(null);
		try {
			req.getRequestDispatcher(redirectTo).forward(req, resp);
		} catch (ServletException e) {
			throw new RuntimeException("Fatal technical Exception");
		} catch (IOException e) {
			throw new RuntimeException("Fatal technical Exception");
		}
	}

}
